<?php

namespace App\Admin\Rules;

use App\Admin\Models\SystemModel;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;

class SystemModelValue implements Rule
{
    protected $errorMessage;

    /**
     * Create a new rule instance.
     *
     * @param string $type
     *
     * @return void
     */
    public function __construct(string $modelId = null)
    {
        $this->modelId = $modelId;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     *
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $modelSlug = SystemModel::whereId($this->modelId)->value('slug');
        // 验证查询是否存在异常
        try {
            DB::select("SELECT {$value} FROM {$modelSlug} Limit 1");
        } catch (\Exception $e) {
            $this->errorMessage = $e->getMessage();
            return false;
        }

        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->errorMessage;
    }
}
